// 页面API服务
const path = require("path");
const fse = require("fs-extra");

// 递归处理函数
const dep = async (comm, fun) => {
  if (!Array.isArray(comm) || comm.length === 0) return;

  const promises = comm.map(async (a) => {
    try {
      await fun(a);
      if (a.children && Array.isArray(a.children) && a.children.length > 0) {
        await dep(a.children, fun);
      }
    } catch (error) {
      console.error(`处理项目 ${JSON.stringify(a)} 时出错:`, error);
      throw error; // 根据需求决定是否重新抛出错误
    }
  });

  return await Promise.all(promises);
};

// URL 转换为驼峰命名
const toHump = (str) => {
  return str
    .replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) =>
      index === 0 ? letter.toLowerCase() : letter.toUpperCase()
    )
    .replace(/\s+/g, "")
    .replace(/\//g, "");
};

// 生成 API 文件
const generateApiFile = async (projectCode, apiUrl, apiType = "get") => {
  const dir = path.resolve(__dirname, `../../../projects/${projectCode}/src/apis/${apiUrl}.js`);
  const gs = apiType === "get" ? "params" : "data";
  const url = apiType === "put" || apiType === "delete" ? `${apiUrl}/\${data.id}` : apiUrl;
  const http = `return http({
    method: "${apiType}",
    url: \`${url}\`,
    ${gs}
  });`;

  const functionName = toHump(apiUrl);
  const content = `export const ${functionName} = (${gs} = {}) => {
    ${http}
  };`;

  // 检查文件是否存在并写入内容
  if (!fse.pathExistsSync(dir)) {
    await fse.outputFileSync(dir, content, "utf8");
  } else {
    const existingContent = await fse.readFileSync(dir, "utf8");
    if (existingContent !== content) {
      await fse.outputFileSync(dir, content, "utf8");
    }
  }
};

// 将 API 加入到项目
const joinApisToProject = async (projectCode, comm) => {
  return new Promise(async (resolve) => {
    if (comm.options && comm.options.indexOf("Filters") === -1) {
      comm.apiUrl = comm.options;
      comm.apiType = "get";
    }
    if (comm.componentKey === "table") {
      if (comm.pagination && comm.pageSize) {
        comm.pagination = {
          show: true,
          pageSize: comm.pageSize,
          pageIndex: 1,
          showQuickJumper: true,
          showSizeChanger: true,
        };
        delete comm.pageSize;
      }
    }
    if (comm.apiUrl && typeof comm.apiUrl === "string") {
      const apis = comm.apiUrl.split("|");
      await dep(apis, async (apiUrl) => {
        const [url, type = "get"] = apiUrl.split(":");
        await generateApiFile(projectCode, url, type);
      });
    }
    resolve();
  });
};

module.exports = joinApisToProject;
